<template>
  <div class="chart-container" ref="container">
    <p class="chart-title">炉体热负荷类别汇总</p>
    <div ref="chartElement" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "TemperatureChart2",
  props: {
    baseCategories: {
      type: Array,
      default: () => []
    },
    currentData: {
      type: Object,
      default: () => ({ yAxisData: [], percentage: [], yLabel: [] })
    },
  },
  data() {
    return {
      chartInstance: null,
      baseFontSize: 12, // Base font size (will be scaled)
      containerObserver: null,
      options: {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>';
            params.forEach(item => {
              const value = (item.value !== undefined && item.value !== null) ?
                  item.value + (item.seriesType === 'bar' ? '%' : '×10MJ/h') : 'N/A';
              result += item.marker + item.seriesName + '类: ' + value + '<br/>';
            });
            return result;
          }
        },
        grid: [],
        xAxis: [],
        yAxis: [],
        series: [],
        color: [
          '#82daff',
          '#a0c782',
          '#caa5ce',
          '#93acc4',
          '#f8d3a3',
          '#f8a3a3',
          '#b7537b'
        ],
        animation: true
      }
    };
  },
  mounted() {
    this.initChart();
    this.setupResizeObserver();
    window.addEventListener('resize', this.handleResize);
    this.updateChart();
  },
  beforeDestroy() {
    if (this.containerObserver) {
      this.containerObserver.disconnect();
    }
    window.removeEventListener('resize', this.handleResize);
    this.chartInstance?.dispose();
  },
  watch: {
    baseCategories: {
      deep: true,
      handler() {
        this.updateChart();
      }
    },
    currentData: {
      deep: true,
      handler() {
        this.updateChart();
      }
    },
  },
  methods: {
    initChart() {
      if (!this.$refs.chartElement) return;
      this.chartInstance = echarts.init(this.$refs.chartElement);
    },
    setupResizeObserver() {
      if (window.ResizeObserver && this.$refs.container) {
        this.containerObserver = new ResizeObserver(entries => {
          for (let entry of entries) {
            this.calculateFontSize(entry.contentRect);
            this.updateChart();
          }
        });
        this.containerObserver.observe(this.$refs.container);
      }
    },
    calculateFontSize(rect) {
      // Calculate base font size based on container dimensions
      const scaleFactor = Math.min(rect.width / 500, rect.height / 400);
      this.baseFontSize = Math.max(10, Math.min(16, 12 * scaleFactor));
    },
    updateChart() {
      if (!this.chartInstance || !this.baseCategories?.length) return;
      // Clear previous configuration
      const newOptions = {
        grid: [],
        xAxis: [],
        yAxis: [],
        series: [],
        color: this.options.color,
        tooltip: this.options.tooltip
      };


      // Calculate the number of charts we need (equal to baseCategories length)
      const chartCount = this.baseCategories.length;
      const rows = Math.ceil(chartCount / 2);
      const heightPercent = 94 / rows;
      const gap = 5; // gap between charts in percentage

      // Create grids for each chart (2 per row)
      for (let i = 0; i < chartCount; i++) {
        const row = Math.floor(i / 2);
        const col = i % 2;

        newOptions.grid.push({
          left: col === 0 ? '1%' : '49%',
          right: col === 0 ? '55%' : '8%',
          top: `${row * heightPercent + gap}%`,
          height: `${heightPercent - gap}%`,
          containLabel: true
        });
      }

      // Calculate the maximum value across all series
      let maxValue = 0;
      this.baseCategories.forEach(category => {
        const categoryMax = Math.max(...category.lineData);
        if (categoryMax > maxValue) {
          maxValue = categoryMax;
        }
      });

      // Round up to the nearest 100
      const roundedMaxValue = Math.ceil(maxValue / 100) * 100;

      // Create xAxes (only show on the last row)
      for (let i = 0; i < chartCount; i++) {
        const isLastRow = true;

        newOptions.xAxis.push({
          type: 'value',
          name: isLastRow ? '热负荷(×10MJ/h)' : '',
          nameRotate: 0,
          nameLocation: 'middle',
          nameGap: 25,
          nameTextStyle: {
            fontSize: this.baseFontSize
          },
          axisLabel: {
            show: isLastRow,
            fontSize: this.baseFontSize - 2,
            formatter: '{value}'
          },
          axisLine: {
            show: isLastRow,
            lineStyle: { color: '#000', type: 'solid', width: 2 }
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#ccc'
            }
          },
          boundaryGap: [0, 0.01],
          min: 0, // Set minimum value to 0
          max: roundedMaxValue, // Set maximum value to the rounded max value
          position: 'bottom',
          gridIndex: i
        });
      }

      // Create yAxes for each chart with original content
      this.baseCategories.forEach((category, index) => {
        newOptions.yAxis.push({
          name: category.name+"类",
          nameLocation: 'end',
          nameGap: 17,
          type: 'category',
          data: ['CP01~10', 'CP11~20', 'CP21~30', 'CP31~42', 'CP43~54','R段'],
          inverse: true,
          axisTick: { show: false },
          axisLine: {
            show: true,
            lineStyle: { color: '#000', type: 'solid', width: 2 }
          },
          axisLabel: {
            fontSize: this.baseFontSize
          },
          splitLine: { show: false },
          gridIndex: index
        });
      });

      // Add base categories data
      this.baseCategories.forEach((category, index) => {
        const categoryName = category.name;
        const lineData = category.lineData.slice().reverse();

        newOptions.series.push({
          name: categoryName,
          type: 'line',
          data: lineData,
          smooth: true,
          lineStyle: {
            type: 'solid',
            width: 2
          },
          symbol: 'circle',
          symbolSize: this.baseFontSize * 0.8,
          xAxisIndex: index,
          yAxisIndex: index,
          itemStyle: {
            color: this.options.color[index % this.options.color.length],
            borderWidth: 1,
            borderColor: '#fff'
          },
          label: {
            show: false,
            fontSize: this.baseFontSize
          },
          emphasis: {
            itemStyle: {
              color: this.options.color[index % this.options.color.length],
              borderWidth: 2,
              borderColor: '#fff',
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        });
      });

      this.chartInstance.setOption(newOptions, true);
      this.handleResize();
    },
    handleResize() {
      this.chartInstance?.resize();
    }
  }
};
</script>

<style scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 300px;
  min-width: 400px;
}

.chart-title {
  text-align: center;
  margin: 2px 0; /* 减小上下边距 */
  font-size: 0.9em; /* 减小字体大小 */
  font-weight: bold;
  color: #333;
  line-height: 1.2; /* 减小行高 */
}

.chart {
  width: 100%;
  height: calc(100% - 40px);
  position: absolute;
  bottom: 0;
}
</style>
